import React, { Component } from "react";
import { Modal, Form, Input, Button, message } from "antd";
import { withRouter } from "react-router-dom";
import { JSEncrypt } from "../../../utils/jsencrypt.js";
import { PUBLI_KEY, PWD_REGEX } from "../../../utils/constants";

const FormItem = Form.Item;

class TradePassword extends Component {
  constructor(props) {
    super(props);
    this.state = {
      confirmDirty: false,
      disabled: false,
      number: 59
    };
  }

  request = window.request;

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { exPassword, password, code } = values;
        let encrypt = new JSEncrypt();
        encrypt.setPublicKey(PUBLI_KEY);
        let enExPassword = encrypt.encrypt(exPassword);
        let enLoginPassword = encrypt.encrypt(password);

        this.request("/user/updateExPassword", {
          method: "POST",
          body: {
            exPassword: enExPassword,
            password: enLoginPassword,
            code
          }
        }).then(json => {
          if (json.code === 10000000) {
            message.success(json.msg);
            this.props.onCancel();

            const account = JSON.parse(sessionStorage.getItem("account"));
            account.exPassword = true;
            sessionStorage.setItem("account", JSON.stringify(account));
            this.props.history.push("/user/security");
          } else {
            message.destroy();
            message.error(json.msg);
          }
        });
      }
    });
  };

  comparePassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue("exPassword")) {
      callback("两次密码不一致");
    } else {
      callback();
    }
  };
  handleConfirmBlur = e => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  validateToNextPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(["confirm"], { force: true });
    }
    callback();
  };

  countDown = () => {
    this.setState({
      disabled: true
    });
    this.timer = setInterval(() => {
      let { number } = this.state;
      if (number === 0) {
        clearInterval(this.timer);
        this.setState({
          number: 59,
          disabled: false
        });
      } else {
        this.setState({ number: number - 1 });
      }
    }, 1000);
  };

  // 获取手机验证码
  getMobileCode = () => {
    this.sendMobileSms();
    this.countDown();
  };

  //发送手机短信
  sendMobileSms = () => {
    this.request("/user/mobile/sendMobileSms", {
      method: "POST",
      body: {
        smsType: "ex_password"
      }
    }).then(json => {
      if (json.code === 10000000) {
        message.success(json.msg);
      }
    });
  };

  render() {
    const { disabled, number } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 18 },
        sm: { span: 18 }
      }
    };
    const { title } = this.props;
    return (
      <Modal
        title={title}
        visible
        width={500}
        wrapClassName="change-pwd-modal v-center-modal"
        onCancel={this.props.onCancel}
        footer={null}
      >
        <Form onSubmit={this.handleSubmit} className="change-password">
          <Input style={{ display: "none" }} type="password" />

          <FormItem {...formItemLayout} label="交易密码">
            {getFieldDecorator("exPassword", {
              rules: [
                { required: true, message: "请输入交易密码" },
                {
                  pattern: /^\d{6}$/,
                  message: "请输入6位数字交易密码"
                },
                { validator: this.validateToNextPassword }
              ],
              validateTrigger: "onBlur"
            })(
              <Input size="large" type="password" placeholder="输入6位数字" />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="确认交易密码">
            {getFieldDecorator("confirm", {
              rules: [
                { required: true, message: "请再次输入交易密码" },
                { validator: this.comparePassword }
              ],
              validateTrigger: "onBlur"
            })(
              <Input
                size="large"
                type="password"
                placeholder="输入6位数字"
                onBlur={this.handleConfirmBlur}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="登录密码">
            {getFieldDecorator("password", {
              rules: [
                { required: true, message: "请输入登录密码" },
                {
                  pattern: PWD_REGEX,
                  message: "输入8-20位密码 包含数字，字母"
                }
              ],
              validateTrigger: "onBlur"
            })(
              <Input
                size="large"
                type="password"
                placeholder="请输入登录密码"
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="短信验证码" className="code-row">
            {getFieldDecorator("code", {
              rules: [
                { required: true, message: "请输入手机验证码" },
                { pattern: /^\d{6}$/, message: "请输入6位数字验证码" }
              ],
              validateTrigger: "onBlur"
            })(<Input size="large" placeholder="短信验证码" />)}
            <Button
              onClick={this.getMobileCode}
              className="get-mobile-code"
              type="primary"
              size="large"
              disabled={disabled}
              style={{ width: 120 }}
            >
              {!disabled ? "获取验证码" : number + "s"}
            </Button>
          </FormItem>

          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            <Button
              type="primary"
              htmlType="submit"
              onClick={this.handleSubmit}
              style={{ width: 100, height: 36 }}
            >
              确认
            </Button>
          </div>
        </Form>
      </Modal>
    );
  }
}

export default withRouter(Form.create()(TradePassword));
